package com.iecas.launch;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.socket.nio.NioClient;
import com.iecas.handler.DefaultClientChannelHandler;
import lombok.Data;

import javax.swing.*;
import java.io.IOException;
import java.nio.ByteBuffer;

@Data
public class Client {
    NioClient nioClient;
    LoginFrame loginFrame;
    GameFrame gameFrame;

    public Client() {
        loginFrame = new LoginFrame();
        loginFrame.setClient(this);
        nioClient = new NioClient("127.0.0.1",20000);
        nioClient.setChannelHandler(new DefaultClientChannelHandler(this));
        nioClient.listen();
    }

    public void write(ByteBuffer encode) {
        try {
//            System.out.println(encode);
            encode.flip();
            nioClient.write(encode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showGameFrame() {
        gameFrame = new GameFrame();
        gameFrame.setClient(this);
    }

    public void close(){
        gameFrame.stopSendHeartBeat();
        loginFrame.dispose();
        gameFrame.dispose();
        nioClient.close();
    }

    public void closeLoginFrame() {
        loginFrame.setVisible(false);
    }

    public NioClient start() {
        return nioClient;
    }

    public void stop() {
        if (ObjectUtil.isNotNull(nioClient)) {
            nioClient.close();
            Console.log("nioClient closed");
        } else {
            Console.log("nioClient not running");
        }
    }

    public static void main(String[] args) throws IOException {
        SwingUtilities.invokeLater(Client::new);

    }
}
